<template>
  <div id="stainingResultDiv">

    <el-tabs v-model="activeName" type="card" class="lab-bac-test-result-tab el-tab-sm" @tab-click="tabHandleClick">
      <el-tab-pane label="染色操作" name="first"></el-tab-pane>
      <el-tab-pane label="过程记录" name="second"></el-tab-pane>
    </el-tabs>

    <div id="transResult" v-show="activeName === 'first'">
      <vxe-toolbar class-name="bg-grey light">
        <template #buttons>
          <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="下一步" @click="addStainingMethodDialog(null)" :disabled='resultIsDisabled()'></vxe-button>
          <el-dropdown trigger="click">
            <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="继续培养" split-button :disabled='resultIsDisabled()'>
              继续培养
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </vxe-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="(item, index) in bacDescOptionList" :key="index" @click="continuousCultivation(item)">
                  <span>{{ item.proResultNa }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="发布报告" @click="publishSecReport" :disabled='resultIsDisabled()'></vxe-button>
          <vxe-button type="text" class="button-red margin-lr-xs" class-name="margin-lr-xs" content="撤销报告" @click="cancelSecReport" :disabled='resultIsDisabled()'></vxe-button>
          <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="打印" @click="quietPrint()"> </vxe-button>
          <vxe-button type="text" class="button-blue margin-lr-xs" class-name="margin-lr-xs" content="预览" @click="previewPrint()"> </vxe-button>
        </template>
      </vxe-toolbar>
        <vxe-table ref="bacDrugTestResultRef" height="auto" border show-overflow :header-cell-style="setBacDrugTestResultHeaderCellStyle" :data="stainingResultList" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showIcon: false }" @current-change="stainingMethodCellClick" :expand-config="{ expandAll: true, reserve: true }" :tree-config="{
              expandAll: true,
              transform: true,
              rowField: 'id',
              parentField: 'parentId'
            }" :menu-config="tableMenu" @menu-click="contextMenuClickEvent" resizable keep-source @cell-dblclick="bacDrugTestRowClick" :cell-style="stainingResultCellColor" :checkbox-config="{
              visibleMethod: showCheckboxkMethod,
              checkMethod: checCheckboxkMethod
              }">
          <vxe-column type="seq" width="30"></vxe-column>
          <vxe-column type="checkbox" width="30" align="center"></vxe-column>
          <vxe-column title="" width="30" align="left">
            <template #default="{ row }">
              <vxe-button v-if="row.handleType != 0" type="text" title="添加子级" status="primary" icon="vxe-icon-square-plus" circle @click="addStainingMethodDialog(row.id)"></vxe-button>
            </template>
          </vxe-column>
          <vxe-column field="handleType" title="类型" width="100" tree-node>
            <template #default="{ row }">
              <span>{{ getIsStaticStatusDesc(row.handleType) }}</span>
            </template>
          </vxe-column>
          <vxe-column field="stainingMethNa" title="操作内容" min-width="120px">
            <template #default="{ row }">
            <span v-if="row.handleType == 0 && row.stainingConcOptNa && !row.isDefault">{{ row.stainingMethNa + row.stainingConcNa +
            row.stainingConcOptNa }}</span>
              <span v-if="row.handleType == 0 && !row.stainingConcOptNa && !row.isDefault == 1">{{ row.stainingMethNa }}</span>
              <span v-if="row.handleType == 0 && !row.stainingConcOptNa && !row.isDefault == 1" style="color: blue">(双击弹窗编辑染色结果)</span>
              <span v-if="row.handleType == 0 && !row.stainingConcOptNa && !row.isDefault == 1">{{ row.stainingConcNa }}</span>
              <span v-if="row.handleType == 1 || row.handleType == 2">{{ row.descText + (row.culMediumNa ? '，' +
                  row.culMediumNa : '') }}</span>
              <span v-if="row.handleType == 0 && row.isDefault == 1">{{ row.descText }}</span>
              <span v-if="row.handleType == 3">{{ row.descText }}</span>
            </template>
          </vxe-column>
          <vxe-column field="isPushSecReport" title="是否发布" width="130">
            <template #default="{ row }">
              <el-tag :type="getIsPushSecReportType(row)">{{ getIsPushSecReportDesc(row) }}</el-tag>
            </template>
          </vxe-column>
          <vxe-column field="createTime" title="操作时间" width="130">
            <template #default="{ row }">
              <span>{{ row.createTime }}</span>
            </template>
          </vxe-column>
          <vxe-column field="userName" title="操作人" width="75" align="center"></vxe-column>
          <vxe-column field="isAlarm" title="危急值" width="75" align="center">
            <template #default="{ row }">
              <span v-if="row.isAlarm == 1" style="color: red">{{ `是` }}</span>
              <span v-else>{{ `否` }}</span>
            </template>
          </vxe-column>
          <!-- <vxe-column title="操作" fixed="right" width="80">
                <template #default="{ row }">
                  <el-select v-model="row.handleType" placeholder="下拉选择">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" @click="selectChange(item)" />
                  </el-select>
                </template>
              </vxe-column> -->
        </vxe-table>
    </div>
    <BacProcessRecords ref="BacProcessRecordsRef" v-if="activeName === 'second'" :businessType="'node3'" />

    <el-dialog title="染色方法" :show-close="false" v-model="showDialog" width="90vw" :close-on-click-modal="false" destroy-on-close v-if="showDialog" class="dyeingMethodDialog">
      <div class="dyeingMethodBodyDialog">
        <div class="dialogHeader">
          <div class="headerTitle">培养基</div>
          <div class="headerRadioGroup" v-if="bacCultureCombinationList.length > 0">
            <el-radio-group v-model="radioValue">
              <el-radio :label="val.id" :value="val.id" v-for="(val, i) in bacCultureCombinationList" :key="i">{{
                val.cultrueNa }}</el-radio>
            </el-radio-group>
          </div>
          <el-divider />
        </div>
        <div class="dialogBody">
          <div class="bodyRadioGroup">
            <el-radio-group v-model="radio1" @change="radioChange">
              <el-radio :label="'0'">涂片</el-radio>
              <el-radio :label="'2'">转种</el-radio>
              <el-radio :label="'1'">分纯</el-radio>
            </el-radio-group>
          </div>
          <div class="tablesDiv">
            <Splitpanes class="area" v-if="boolFlag">
              <Pane size="35">
                <vxe-table ref="methodTableRef" border align="left" class="mytable-scrollbar" resizable :loading="loading" height="auto" :data="methodTableData" :edit-config="{ trigger: 'click', mode: 'cell' }" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @current-change="methodTableCellClick">
                  <vxe-column type="checkbox" width="26"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="methodCode" title="编号"></vxe-column>
                  <vxe-column field="methodName" title="染色方法"></vxe-column>
                  <vxe-column field="description" title="描述"></vxe-column>
                  <vxe-column field="inputCode" title="助记符"></vxe-column>
                </vxe-table>
              </Pane>
              <Pane size="65">
                <vxe-table ref="conclusionTableRef" border align="left" class="mytable-scrollbar" resizable :edit-config="{ trigger: 'click', mode: 'cell' }" :loading="loading" height="auto" :data="conclusionTableData" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }" @checkbox-change="onConclusionCheckboxChange">
                  <vxe-column type="checkbox" width="26" @checkbox-change="onConclusionCheckboxChange"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="conclusionCode" title="编号"></vxe-column>
                  <vxe-column field="conclusionName" title="染色结论"></vxe-column>
                  <vxe-column field="clinicalSignificance" title="临床意义"></vxe-column>
                  <vxe-column field="inputCode" title="助记符"></vxe-column>
                </vxe-table>
              </Pane>
            </Splitpanes>
            <Splitpanes class="area1" v-else>
              <Pane>
                <vxe-table ref="cultureCombinationRef" border align="left" class="mytable-scrollbar" resizable height="auto" :loading="loading" :data="cultureCombinationData" :edit-config="{ trigger: 'click', mode: 'cell' }" :row-config="{ isCurrent: true }" :column-config="{ resizable: true }" show-overflow keep-source :scroll-y="{ enabled: true }">
                  <vxe-column type="checkbox" width="26"></vxe-column>
                  <vxe-column type="seq" title="#" width="30"></vxe-column>
                  <vxe-column field="code" title="培养基组合编码"></vxe-column>
                  <vxe-column field="name" title="培养基组合名称"></vxe-column>
                  <vxe-column field="inputCode" title="助记符"></vxe-column>
                </vxe-table>
              </Pane>
            </Splitpanes>
          </div>
          <div class="dialog-footer flex right justify-end" style="margin: 10px 0 10px 0">
            <el-button type="primary" @click="saveBacthStaining()">确定</el-button>
            <el-button @click="closeDialog()">取消</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <vxe-modal v-model="stainResultDialog" title="染色结果" :mask="false" width="40vw" height="25vh" :destroy-on-close="true" show-zoom resize>
      <template #title>
        <span>选择染色结果</span>
      </template>
      <template #default>
        <vxe-form title-width="90" :data="currentStainResult" title-align="right" span="23">
          <vxe-form-item title="染色方法" field="iqcMaterialId">
            <template #default="{ data }">
              <vxe-input v-model="data.stainingMethNa" disabled></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="染色结果" field="iqcMaterialId">
            <template #default="{ data }">
              <vxe-select v-model="data.stainingConcOptNo" transfer>
                <vxe-option v-for="item in stainOptions" :key="item.resultCode" :value="item.resultCode" :label="item.resultName"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title=" " field="isAlarm">
            <template #default="{ data }">
              <vxe-checkbox v-model="data.isAlarm" content="危急值" :checked-value="1" :unchecked-value="0" @change="criValueChange"></vxe-checkbox>
              <span class="margin-lr">&nbsp;</span>
              <vxe-checkbox v-model="currentStainResult.isPushSecReport" content="发布二级报告" :checked-value="1" :unchecked-value="0"></vxe-checkbox>
            </template>
          </vxe-form-item>
          <vxe-form-item align="right">
            <vxe-button status="primary" @click="saveCurrentStainResult">确定</vxe-button>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-modal>

    <vxe-modal v-model="secReportDialog" title="发布报告" :mask="false" width="70vw" height="70vh" :destroy-on-close="true" show-zoom resize>
      <template #default>
        <BacSecReport ref="refBacSecReport"></BacSecReport>
        <div class="flex justify-end" style="margin-top: 20px">
          <vxe-button type="text" class="button-blue margin-left-xs" content="确定" @click="confirmSecReportV1"></vxe-button>
          <vxe-button type="text" class="button-white margin-left-xs" content="取消" @click="secReportDialog = false"></vxe-button>
        </div>
      </template>
    </vxe-modal>

    <AuthValidateComp ref="AuthValidateCompRef" @unChkConfirm="validatePermisionFinish" />
    <MultiRptPreviewFixId :reportList="reportList" :toggle="isPreviewRpt" :modalTitle="'染色报告预览'" />

    <!-- 静默打印 -->
    <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />

  </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, getCurrentInstance, defineProps } from 'vue';
import { formatDateTime, IsEmpty } from '@/utils/common';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import BacProcessRecords from './BacProcessRecords.vue';
let { proxy }: any = getCurrentInstance();
import { Splitpanes, Pane } from 'splitpanes';
import AuthValidateComp from '@/components/AuthValidateComp.vue';
import { getOptionValueByCodeRptGroupOption, getOptionValueByCodeGlobalOption } from '@/utils/SysOptionsHelper';
import BacSecReport from './BacSecReport.vue';
import MultiRptPreviewFixId from '@/components/MultiRptPreviewFixId.vue';
import QuietPrint from '@/components/QuietPrint.vue';
import {saveProcessLogs} from "@/utils/BacProcessLogHelper";
defineExpose({
  initPage
});
let tableMenu = {
  className: 'my-menus',
  body: {
    options: [[{ code: 'remove', name: '删除', prefixIcon: 'vxe-icon-delete color-red' }]]
  }
};
let labMainInfoObj: any = reactive({}); /**检验记录当前选中对象 */
let activeName = ref('first');
let radio1 = ref('0');
let boolFlag = ref(true);
let bacDescOptionList: any[] = reactive([]); /**继续培养 */
let stainingResultList: any = reactive([]); //染色方法数据
let radioValue = ref('01');
let stepNodeObj: any = reactive({}); /**当前选中流程节点对象 */
const AuthValidateCompRef = ref(null); /**发布二级报告 授权验证 */
let secReportMustSelectStaing = ref(''); /* 二级报告必须选择染色方法 */
const BacProcessRecordsRef = ref(null); /**过程记录对象 */
/**初始化界面 */
function initPage(mainInfoRow: any, stepNode: any, sltWorkFlow: any) {
  const a = getOptionValueByCodeRptGroupOption('wswfbejbgbxxzrsgc');
  secReportMustSelectStaing.value = a;
  Object.assign(labMainInfoObj, mainInfoRow);
  Object.assign(sltWorkFlowObj, sltWorkFlow);
  Object.assign(stepNodeObj, stepNode);
  findBacDescOptionList();
  findStainingResult();
}

const methodId: any = ref(null);
let bacCultureCombinationList: any[] = reactive([]); /**培养基 */
let showDialog = ref(false); //添加弹框展示状态

//查询菌株下的染色结果
function findStainingResult() {
  let data = {
    rptGroup: labMainInfoObj.rptGroup,
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    sampleNo: labMainInfoObj.sampleNo
  } as any;
  stainingResultList.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-staining-result/findBacStainingResultListBySampleNo';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { params: data })
    .then((res: any) => {
      stainingResultList.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结果列表数据异常', VxeNotifyType.error);
    });
}

// 添加染色方法
function addStainingMethodDialog(id) {
  methodId.value = id;
  findCultureInfo();
  if (radio1.value == '0') {
    boolFlag.value = true;
    findStainingMethod();
  } else {
    boolFlag.value = false;
    findCultureCombination();
  }
  showDialog.value = true;
}

function tabHandleClick(tab) {
  if (tab.paneName === 'second') {
    setTimeout(() => {
      BacProcessRecordsRef.value?.initRecords(labMainInfoObj, stepNodeObj);
    }, 200);
  }
}
// 弹框取消按钮
function closeDialog() {
  showDialog.value = false;
}
//查询当前标本下的培养基
function findCultureInfo() {
  bacCultureCombinationList.length = 0;
  const url = '/api/bac/bac-culture-medium/findBacCultureMediums';
  // let data = { searchValue: '' } as any;
  proxy.$http
    .get(url, { params: { maininfoId: labMainInfoObj.id, rptGroup: labMainInfoObj.rptGroup, sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'), sampleNo: labMainInfoObj.sampleNo } })
    .then((res: any) => {
      if (res && res.data) {
        for (const irow of res.data) {
          bacCultureCombinationList.push({
            cultrueId: irow.code,
            cultrueNa: irow.name,
            id: irow.code
          });
        }
        //findBacCultureMediumList();
      }
    })
    .catch((err: any) => {});
}

//根据父组件传过来的培养基组合ID获取所有培养基
function findBacCultureMediumList() {
  const cultureCombinationList: any[] = [];
  if (IsEmpty(sltWorkFlowObj._value.cultureCombinationIds)) {
    return;
  }
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationListByIds';
  proxy.$http
    .get(url, { params: { ids: sltWorkFlowObj._value.cultureCombinationIds && sltWorkFlowObj._value.cultureCombinationIds.length > 0 ? sltWorkFlowObj._value.cultureCombinationIds : [] } })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        cultureCombinationList.push(...res.data);
        for (const irow of cultureCombinationList) {
          bacCultureCombinationList.push({
            cultrueId: irow.code,
            cultrueNa: irow.name,
            id: irow.code
          });
        }
      }
    })
    .catch((err: any) => {});
}
let leftCurrentRow = reactive({}); //左侧表格选中的当前行
let methodTableData: any = reactive([]); //弹框染色方法
const methodTableRef = ref(null); /**表格ref标记*/
let sltWorkFlowObj: any = reactive({}); /**当前选中流程节点对象 */

function findStainingMethod() {
  loading.value = true;
  methodTableData.length = 0; /**放入数据前清空数据*/
  const url = '/bac/staining/method/findStainingMethodList';
  proxy.$http
    /**注意此处的数据条数*/
    .get(url, { keyWords: form.keyvalue })
    .then(async (res: any) => {
      methodTableData.push(...res.data);
      loading.value = false;
      if (res && res.data && res.data.length > 0) {
        const newSelRow = res.data[0];
        leftCurrentRow = newSelRow;
        methodTableCellClick({ row: newSelRow });
        const $table = methodTableRef.value;
        if ($table) {
          await $table.setCurrentRow(newSelRow);
        }
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色方法列表数据异常', VxeNotifyType.error);
    });
}

const loading = ref(false); /**刷新+表格加载*/
let cultureCombinationData: any = reactive([]); //弹框培养基组合

//获取分纯,转种数据
function findCultureCombination() {
  loading.value = true;
  cultureCombinationData.length = 0; /**放入数据前清空数据*/
  const url = '/api/bac/bac-cultrue-combination/findBacCultureCombinationListByType';
  const a = {
    type: radio1.value
  };
  proxy.$http
    .get(url, { params: a })
    .then(async (res: any) => {
      cultureCombinationData.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色方法列表数据异常', VxeNotifyType.error);
    });
}
let currentRow: any = reactive({ id: '', code: '' });

/**表格选中当前行*/
function methodTableCellClick({ row }) {
  //BacStainingConclusionRef.value?.tempSelectChange(row);
  Object.assign(currentRow, row);
  leftCurrentRow = row;
  findStainingConclusionList(currentRow);
  proxy.$forceUpdate();
}

let conclusionTableData: any = reactive([]); //弹框表格数据
let form: any = reactive({
  autocalc: false
});
function findStainingConclusionList(row) {
  loading.value = true;
  conclusionTableData.length = 0; /**放入数据前清空数据*/
  const url = '/bac/staining/conclusion/findStainingConclusionList';
  /**注意此处的数据条数*/
  const a = {
    keyWords: form.keyvalue,
    stainingMethodId: row.methodCode
  };
  proxy.$http
    .get(url, { params: a })
    .then(async (res: any) => {
      conclusionTableData.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结论列表数据异常', VxeNotifyType.error);
    });
}

//继续培养
function findBacDescOptionList() {
  bacDescOptionList.length = 0;
  if (IsEmpty(labMainInfoObj.id)) {
    return;
  }
  const url = '/bac-cul-pro-result/findBacDescOptionList';
  let data = { searchValue: '' } as any;
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      if (res && res.data && res.data.length >= 0) {
        Object.assign(bacDescOptionList, res.data);
      }
    })
    .catch((err: any) => {});
}
let stainingResultTableDate: any = reactive([]); //弹框表格数据

// 弹框保存的确定按钮
function saveBacthStaining() {
  if (IsEmpty(radioValue.value)) {
    VxeMessage('请先选择培养基', VxeNotifyType.error);
    return;
  }
  const bacStainingResultList = [];
  const ids = [];
  if (radio1.value == '0') {
    const methodSelectRows = (proxy.$refs.methodTableRef as any).getCheckboxRecords();
    const selectRows = (proxy.$refs.conclusionTableRef as any).getCheckboxRecords();
    if (selectRows.length > 0) {
      for (const sltRow of selectRows) {
        const mthRow = methodSelectRows.find((n) => (n.methodCode = sltRow.staMethodNo));
        const addQcItem = {
          sampleda: labMainInfoObj.sampleda,
          rptGroup: labMainInfoObj.rptGroup,
          sampleNo: labMainInfoObj.sampleNo,
          maininfoId: labMainInfoObj.id,
          wkFlwId: stepNodeObj.workFlowId,
          testFlowNo: stepNodeObj.testFlowNo,
          wkFlwNodeId: stepNodeObj.workFlowNodeId,
          testNodeNo: stepNodeObj.nodeNo,
          stainingMethNo: mthRow.methodCode,
          stainingConcNo: sltRow.conclusionCode,
          stainingMethNa: mthRow.methodName,
          stainingConcNa: sltRow.conclusionName,
          handleType: radio1.value,
          cultureMediumId: radioValue.value,
          culMediumNo: radioValue.value,
          stainingMethodId: mthRow.id,
          stainingConclusionId: sltRow.id,
          staConclusionNo: sltRow.conclusionCode,
          descText: mthRow.methodName + ',' + sltRow.conclusionName,
          parentId: methodId.value,
          isPushSecReport: 0
        };
        bacStainingResultList.push(addQcItem);
        ids.push(sltRow.id);
      }
    }
  } else {
    const cultureCombinationRows = (proxy.$refs.cultureCombinationRef as any).getCheckboxRecords();

    if (cultureCombinationRows.length > 0) {
      for (const sltRow of cultureCombinationRows) {
        const addQcItem = {
          sampleda: labMainInfoObj.sampleda,
          rptGroup: labMainInfoObj.rptGroup,
          sampleNo: labMainInfoObj.sampleNo,
          maininfoId: labMainInfoObj.id,
          wkFlwId: stepNodeObj.workFlowId,
          testFlowNo: stepNodeObj.testFlowNo,
          wkFlwNodeId: stepNodeObj.workFlowNodeId,
          testNodeNo: stepNodeObj.nodeNo,
          handleType: radio1.value,
          cultureMediumId: radioValue.value,
          culMediumNo: radioValue.value,
          combinationId: sltRow.id,
          culCombinaNo: sltRow.id,
          descText: sltRow.name,
          parentId: methodId.value,
          isPushSecReport: 0
        };
        bacStainingResultList.push(addQcItem);
      }
    }
  }
  const pyjStr = bacCultureCombinationList
    .filter((p) => p.id === radioValue.value)
    .map((p) => p.cultrueNa)
    .join(' ');
  const centStr = bacStainingResultList.map((p) => p.descText).join('\n');
  let actStr = '';
  if (!IsEmpty(radio1.value) && radio1.value === '0') {
    actStr = `【涂片】`;
  }
  if (!IsEmpty(radio1.value) && radio1.value === '1') {
    actStr = `【分纯】`;
  }
  if (!IsEmpty(radio1.value) && radio1.value === '2') {
    actStr = `【转种】`;
  }
  if (bacStainingResultList.length > 0) {
    const url = '/api/bac/bac-staining-result/batchAddBacStainingResult';
    proxy.$http
      .post(url, bacStainingResultList)
      .then((res: any) => {
        findStainingResult(); // 刷新结果表格
        if (res && res.status && res.status.code === 1) {
          try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const contentSrr = [`【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】添加步骤\n`, !IsEmpty(pyjStr) ? '培养基: ' + pyjStr + '' : '', !IsEmpty(actStr) ? '' + actStr + '' : '', !IsEmpty(centStr) ? '' + centStr + '' : ''].filter(Boolean).join('\n');
          } catch (error) {}
        }
        VxeMessage(res.status.msg, VxeNotifyType.success);
        radio1.value = '0';
      })
      .catch((err: any) => {
        radio1.value = '0';
        VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    VxeMessage('请选择要添加的数据', VxeNotifyType.error);
  }
  radioValue.value = '';
  findCultureInfo();
  closeDialog();
}

//继续培养
function continuousCultivation(item) {
  const bacStainingResultList = [];
  const addQcItem = {
    sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
    rptGroup: labMainInfoObj.rptGroup,
    sampleNo: labMainInfoObj.sampleNo,
    maininfoId: labMainInfoObj.id,
    wkFlwId: stepNodeObj.workFlowId,
    testFlowNo: stepNodeObj.testFlowNo,
    wkFlwNodeId: stepNodeObj.workFlowNodeId,
    testNodeNo: stepNodeObj.nodeNo,
    handleType: '3',
    cultureMediumId: stepNodeObj.cultureMedium,
    culCombinaNo: stepNodeObj.culCombinaNo,
    descText: item.proResultNa
  };
  bacStainingResultList.push(addQcItem);

  if (bacStainingResultList.length > 0) {
    const url = '/api/bac/bac-staining-result/batchAddBacStainingResult';
    proxy.$http
      .post(url, bacStainingResultList)
      .then((res: any) => {
        findStainingResult(); // 刷新结果表格
        //courseRecord('继续培养');
        if (res && res.status && res.status.code === 1) {
          const a = localStorage.getItem('userInfo');
          const b = JSON.parse(a);
        }
        VxeMessage(res.status.msg, VxeNotifyType.success);
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  } else {
    VxeMessage('请选择要添加的数据', VxeNotifyType.error);
  }
}

//染色结果表格单点事件
function stainingMethodCellClick({ row }) {
  Object.assign(stainingResultTableDate, row);
}
function contextMenuClickEvent({ menu, row, column }) {
  //审核的不能再双击
  if (!IsEmpty(row) && !IsEmpty(row.isPushSecReport) && row.isPushSecReport === 1) {
    VxeMessage('染色结果已发布报告，不能删除', VxeNotifyType.error);
    return;
  }

  const url = '/api/bac/bac-staining-result/deleteBacStainingResult';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      VxeMessage(res.status.msg, VxeNotifyType.success);
      findStainingResult(); // 刷新结果表格
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
let stainOptions = reactive([]);
let stainResultDialog = ref(false);
let currentStainResult: any = reactive({});

// 点击表格当前行
async function bacDrugTestRowClick({ row, $event, column }) {
  //审核的不能再双击
  if (!IsEmpty(row) && !IsEmpty(row.isPushSecReport) && row.isPushSecReport === 1) {
    return;
  }
  if (!IsEmpty(labMainInfoObj) && !IsEmpty(labMainInfoObj.isChk) && labMainInfoObj.isChk === 2) {
    return;
  }

  stainOptions.length = 0;
  if (row.handleType == 0 && column.field == 'stainingMethNa') {
    const url = '/bac/staining/options/findStainingOptionsList';
    let data = { stainingConclusionId: row.staConclusionNo } as any;
    await proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        if (res && res.data && res.data.length >= 0) {
          stainOptions = res.data;
        }
      })
      .catch((err: any) => {});
    Object.assign(currentStainResult, row);
    stainResultDialog.value = true;
  }
}

//染色方法 右侧表格勾选 左侧父级表格自动勾选
function onConclusionCheckboxChange(checkedRows) {
  if (checkedRows.records.length > 0) {
    // 如果右侧 有勾选数据
    checkedRows.records.forEach((row) => {
      // 在左侧表格数据中查找相同数据
      let leftTableRow = methodTableData.find((item) => item.id === row.stainingMethodId);
      if (leftTableRow) {
        // 将左侧表格中对应行的勾选状态设为 true
        proxy.$refs.methodTableRef.setCheckboxRow(leftTableRow, true);
      }
    });
  } else {
    //如果右侧表格没有任何行被勾选 将左侧表格中对应行的勾选状态设为 false
    proxy.$refs.methodTableRef.setCheckboxRow(leftCurrentRow, false);
  }
}

function saveCurrentStainResult({}, iscallback = false) {
  if (iscallback === false && currentStainResult.isPushSecReport === 1) {
    AuthValidateCompRef.value?.initPage('3');
    return;
  }

  const data: any = stainOptions.filter((a) => a.resultCode == currentStainResult.stainingConcOptNo);
  const bacStainingResult = {};
  Object.assign(bacStainingResult, currentStainResult);
  // const aa = {
  //   id: stainingResultTableDate.id,
  //   stainingConcOptNo: data[0].resultCode,
  //   stainingConcOptNa: data[0].resultName,
  //   stainingOptionsId: data[0].id,
  //   isAlarm: currentStainResult.isAlarm
  // };

  bacStainingResult.stainingConcOptNo = data[0].resultCode;
  bacStainingResult.stainingConcOptNa = data[0].resultName;
  bacStainingResult.stainingOptionsId = data[0].resultName;
  bacStainingResult.stainingOptionsId = data[0].id;
  //修改列表数据不刷新
  const result = stainingResultList.filter((p) => p.id == currentStainResult.id);
  result[0].stainingConcOptNa = data[0].resultName;
  result[0].stainingConcOptNo = data[0].resultCode;
  result[0].isAlarm = currentStainResult.isAlarm;
  result[0].isPushSecReport = currentStainResult.isPushSecReport;
  const url = '/api/bac/bac-staining-result/updateBacStainingResult';
  proxy.$http
    /**注意此处的数据条数*/
    .post(url, bacStainingResult)
    .then(async (res: any) => {
      // findStainingResult(strainCurrentRow);
      // courseRecord(`修改${e.resultName}结果`);
      VxeMessage('添加结果成功', VxeNotifyType.success);

      stainResultDialog.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('获取染色结果列表数据异常', VxeNotifyType.error);
    });
}
const bacDrugTestResultRef = ref(null); /**药敏结果列表对象 */
let secReportDialog = ref(false);
let refBacSecReport = ref(null);

/**静默打印执行打印 */
function publishSecReport() {
  const rows = bacDrugTestResultRef.value?.getCheckboxRecords(true);
  if (!rows || rows.length <= 0) {
    VxeMessage('请先勾选染色方法', VxeNotifyType.warning);
    return;
  }
  confirmSecReportV1();
}

/* 确认发布二级报告 */
function confirmSecReportV1() {
  const datas = [];
  const rows = bacDrugTestResultRef.value?.getCheckboxRecords(true);
  if (rows && rows.length > 0) {
    const descStrs = [];
    rows.forEach((element) => {
      const data = {
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: labMainInfoObj.sampleda + ' 00:00:00',
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: stepNodeObj.testFlowNo,
        testNodeNo: stepNodeObj.nodeNo,
        stainingResulId: element.id
      };
      datas.push(data);
      descStrs.push(element.descText);
    });
    const url = '/api/bac/bacPublisSecReport/batchEditPublisSecReport';
    proxy.$http
      .post(url, datas)
      .then((res: any) => {
        VxeMessage('发布成功', VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            const processLogData = {
              strainId: null,
              strainNo: null,
              strainName: null,
              maininfoId: labMainInfoObj.id,
              wkFlwId: null,
              wkFlwNodeId: null,
              rptGroup: labMainInfoObj.rptGroup,
              sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
              sampleNo: labMainInfoObj.sampleNo,
              testFlowNo: labMainInfoObj.testFlowNo,
              testNodeNo: labMainInfoObj.nodeNo,
              content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布染色报告\n`,
              operatorDoctor: IsEmpty(b.username) ? '' : b.username
            };
            saveProcessLogs(processLogData);

            findStainingResult();
          } catch (err) {}
        }
        secReportDialog.value = false;
      })
      .catch((err: any) => {
        VxeMessage('发布失败', VxeNotifyType.success);
      });
  } else {
    const data = {
      rptGroup: labMainInfoObj.rptGroup,
      sampleda: labMainInfoObj.sampleda + ' 00:00:00',
      sampleNo: labMainInfoObj.sampleNo,
      testFlowNo: stepNodeObj.testFlowNo,
      testNodeNo: stepNodeObj.nodeNo,
      stainingResulId: ''
    };
    datas.push(data);
    const descStrs = [];
    const url = '/api/bac/bacPublisSecReport/batchEditPublisSecReport';
    proxy.$http
      .post(url, datas)
      .then((res: any) => {
        VxeMessage('发布成功', VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          try {
            const a = localStorage.getItem('userInfo');
            const b = JSON.parse(a);
            // const contentSrr = [
            //   `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】发布二级报告\n`,
            //   !IsEmpty(formData.morphologyName) ? '结果描述: ' + formData.morphologyName + '' : '',
            //   descStrs && descStrs.length > 0 ? '染色结果: ' + (descStrs.join(',')) + '' : '',
            // ].filter(Boolean).join('\n');
            // courseRecord(`${contentSrr}`);
          } catch (err) {}
        }
        secReportDialog.value = false;
      })
      .catch((err: any) => {
        VxeMessage('发布失败', VxeNotifyType.success);
      });
  }
}

function cancelSecReport() {
  const srList = stainingResultList.filter((row) => !IsEmpty(row.isPushSecReport) && row.isPushSecReport == 1);
  console.log(srList);
  if (srList.length > 0) {
    const datas = [];
    srList.forEach((element) => {
      const data = {
        rptGroup: labMainInfoObj.rptGroup,
        sampleda: labMainInfoObj.sampleda + ' 00:00:00',
        sampleNo: labMainInfoObj.sampleNo,
        testFlowNo: stepNodeObj.testFlowNo,
        testNodeNo: stepNodeObj.nodeNo,
        stainingResulId: element.id
      };
      datas.push(data);
    });

    const url = '/api/bac/bacPublisSecReport/batchCancelSecReport';
    proxy.$http
      .post(url, datas)
      .then((res: any) => {
        VxeMessage('撤销成功', VxeNotifyType.success);
        if (res && res.status && res.status.code === 1) {
          try {
            findStainingResult();
              const a = localStorage.getItem('userInfo');
              const b = JSON.parse(a);
              const processLogData = {
                strainId: null,
                strainNo: null,
                strainName: null,
                maininfoId: labMainInfoObj.id,
                wkFlwId: null,
                wkFlwNodeId: null,
                rptGroup: labMainInfoObj.rptGroup,
                sampleda: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd 00:00:00'),
                sampleNo: labMainInfoObj.sampleNo,
                testFlowNo: labMainInfoObj.testFlowNo,
                testNodeNo: labMainInfoObj.nodeNo,
                content: `【${formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss')}】操作人:【${IsEmpty(b.realname) ? '' : b.realname}】撤销染色报告\n`,
                operatorDoctor: IsEmpty(b.username) ? '' : b.username
              };
              saveProcessLogs(processLogData);
          } catch (err) {}
        }
        secReportDialog.value = false;
      })
      .catch((err: any) => {
        VxeMessage('撤销成功', VxeNotifyType.success);
      });
  } else {
    VxeMessage('暂无撤销的染色报告', VxeNotifyType.error);
  }
}

function radioChange(value) {
  if (value == '0') {
    boolFlag.value = true;
    findStainingMethod();
  } else {
    boolFlag.value = false;
    findCultureCombination();
  }
}
/**选择染色结果   发布危急值  复选框选择改变事件 */
function criValueChange({ checked, $event }) {
  if (checked && currentStainResult.isPushSecReport !== 1) {
    currentStainResult.isPushSecReport = 1;
  }
}
/**染色结果行颜色判断 */
function stainingResultCellColor({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
  if (row && row.isAlarm && (row.isAlarm === 1 || row.isAlarm === '1')) {
    return { color: '#ff0000' };
  }
}
/**设置表头单元格样式 */
function setBacDrugTestResultHeaderCellStyle({ column }) {
  if (column.field === 'r' || column.field === 'i' || column.field === 'sdd' || column.field === 's' || column.field === 'ecoff' || column.field === 'whonetTest' || column.field === 'breakPointRef' || column.field === 'guideline' || column.field === 'year' || column.field === 'germCodeType' || column.field === 'orgCodeType' || column.field === 'germNo' || column.field === 'breakPointType' || column.field === 'host' || column.field === 'infeSite' || column.field === 'refTable' || column.field === 'refTableSeq' || column.field === 'breakPointId') {
    return { fontWeight: 300 };
  }
}
/**发布二级报告验证授权完成 */
function validatePermisionFinish(e) {
  saveCurrentStainResult({}, true);
}
/**判断是否审核，若审核范围ture */
function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return true;
  } else {
    return false;
  }
}
function getIsStaticStatusDesc(row) {
  if (row == 0) {
    return '涂片';
  } else if (row == 1) {
    return '分纯';
  } else if (row == 2) {
    return '转种';
  } else if (row == 3) {
    return '续培';
  } else {
    return '';
  }
}

// 获取是否静态的tag标记(绿/红)
function getIsPushSecReportType(row: any) {
  if (!IsEmpty(row.isPushSecReport) && row.isPushSecReport == 1) {
    return 'success';
  } else {
    return 'danger';
  }
}
// 获取是否静态文字(是/否)
function getIsPushSecReportDesc(row: any) {
  if (!IsEmpty(row.isPushSecReport) && row.isPushSecReport == 1) {
    return '是';
  } else {
    return '否';
  }
}

function checCheckboxkMethod({ row }: any) {
  if (!IsEmpty(row.isPushSecReport) && row.isPushSecReport == 1) {
    return false;
  } else {
    return true;
  }
}

// 弹框 表格复选框(是否允许用户手动勾选)
function showCheckboxkMethod({ row }: any) {
  if (!IsEmpty(row.isPushSecReport) && row.isPushSecReport == 1) {
    return false;
  } else {
    return true;
  }
}
let printParamsObj = ref(null); /**静默打印参数 */

function quietPrint() {
  //先根据路由的URL获取对应的报表信息
  let url = `/api/pubReport/getReportByBusFormCode?code=007`;
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res && res.status && res.status.code === 1 && res.data && !IsEmpty(res.data.id)) {
        printParamsObj.value = [{ Id: new Date().valueOf(), ReportName: res.data.id, ReportParameters: [{ Name: 'Id', Value: labMainInfoObj.id }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }];
      } else {
        proxy.$alert('查无容器条码模板', '提示');
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
const isPreviewRpt = ref(false);
let reportList = reactive([]);

function previewPrint() {
  isPreviewRpt.value = false;
  //先根据路由的URL获取对应的报表信息
  let url = `/api/pubReport/getReportByBusFormCode?code=007`;
  proxy.$http
    .get(url)
    .then((res: any) => {
      const reportId = res.data.id;
      reportList.length = 0;
      const data = {
        id: labMainInfoObj.id,
        reportTemplateName: '染色报告.rdlx',
        reportId: reportId
      };
      reportList.push(data);
      isPreviewRpt.value = true;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
</script>

<style scoped lang="scss">
@import '@/assets/css/el-tabs.scss';
#stainingResultDiv {
  height: 100%;
}
.lab-bac-test-result-tab {
  :deep(.el-tabs__header) {
    margin-bottom: 0;
  }

  :deep(.el-tabs__nav-prev) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__nav-next) {
    line-height: 28px !important;
  }

  :deep(.el-tabs__content) {
    height: 0px;
    padding: 2px;
  }

  :deep(.el-tab-pane) {
    height: 0px;
  }
}
#transResult {
  height: 100%;
}
</style>
